package rexsee.core.progress;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.text.Html;
import android.view.KeyEvent;

public class RexseeProgressDialog implements JavascriptInterface {

	public static final String INTERFACE_NAME = "ProgressDialog";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return childBrowser.progressDialog;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseeProgressDialog(childBrowser);
	}

	private ProgressDialog mProgressDialog = null;

	private final Context mContext;
	private final Browser mBrowser;

	public RexseeProgressDialog(Browser browser) {
		super();
		mBrowser = browser;
		mContext = browser.getContext();
	}
	public void showWithRunnable(final String message, final Runnable cancelRunnable) {
		((Activity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (mProgressDialog == null) {
					mProgressDialog = new ProgressDialog(mContext);
					mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					mProgressDialog.setOnKeyListener(new Dialog.OnKeyListener() {
						@Override
						public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
							if (arg1 == KeyEvent.KEYCODE_SEARCH) return true;
							else return false;
						}
					});
				}
				mProgressDialog.setMessage(Html.fromHtml(message));
				if (cancelRunnable == null) {
					mProgressDialog.setCancelable(false);
				} else {
					mProgressDialog.setCancelable(true);
					mProgressDialog.setCanceledOnTouchOutside(false);
					mProgressDialog.setOnCancelListener(new OnCancelListener() {
						@Override
						public void onCancel(DialogInterface dialog) {
							cancelRunnable.run();
						}
					});
				}
				mProgressDialog.show();
			}
		});
	}

	//JavaScript Interface
	public void show(final String message, final String cancelCallback) {
		if (cancelCallback.equals("")) {
			showWithRunnable(message, null);
		} else {
			showWithRunnable(message, new Runnable() {
				@Override
				public void run() {
					mBrowser.function.load(cancelCallback);
				}
			});
		}
	}
	public void show(final String message) {
		show(message, "");
	}

	public void hide() {
		((Activity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {
					if (mProgressDialog != null) {
						mProgressDialog.dismiss();
						mProgressDialog = null;
					}
				} catch (Exception e) {
				}
			}
		});
	}

}
